import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created with IntelliJ IDEA.
 * Description:dao数据库访问对象
 * User: lenovo
 * Date: 2022-12-14
 * Time: 11:03
 */
public class UserDao {
    //1.登录的时候需要用到 ---根据用户名来获取用户的详情
    //隐含条件:用户性必须唯一
    public User selectByName(String userName){
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet =null;
        User user = null;

        //1.建立连接
        try {
          connection = DbUtil.getConnection();
            //2.构造sql语句
            String sql = "select * from user where userName = ?;";
             statement = connection.prepareStatement(sql);
            statement.setString(1,userName);
            //3.执行sql
            resultSet = statement.executeQuery();
            //4.遍历集合
           if(resultSet.next()){
                user = new User();
                //将数据库里的uesr信息加载到java对象里
                user.setUserName(resultSet.getString("userName"));
                user.setUserId(resultSet.getInt("userId"));
                user.setPassWord(resultSet.getString("passWord"));
                return user;
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            //关闭资源
            DbUtil.close(resultSet,statement,connection);
        }
        //没进if语句说明不存在这个用户,直接返回null
        return null;
    }

    //2.根据用户id获取的到用户的详情 ---在获取用户信息的时候需要用到
    public User selectByUserId(int userId){
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet =null;
        User user = null;

        //1.建立连接
        try {
            connection = DbUtil.getConnection();
            //2.构造sql语句
            String sql = "select * from user where userId = ?;";
            statement = connection.prepareStatement(sql);
            statement.setInt(1,userId);
            //3.执行sql
            resultSet = statement.executeQuery();
            //4.遍历集合
           if(resultSet.next()){
                user = new User();
                //将数据库里的uesr信息加载到java对象里
                user.setUserName(resultSet.getString("userName"));
                user.setUserId(resultSet.getInt("userId"));
                user.setPassWord(resultSet.getString("passWord"));
                return  user;
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            //关闭资源
            DbUtil.close(resultSet,statement,connection);
        }
         //没进if语句说明不存在这个用户,直接返回null
        return null;

    }
    

}
